import logging
import os
from operator import not_, and_
from uuid import uuid4

from info.models import Category, News, User
from . import profile_blu
from info import constants, db
from info.utils.common import user_login_data
from flask import make_response, g, render_template, redirect, request, jsonify, url_for, current_app, abort


@profile_blu.route('/info')
@user_login_data
def user_info():
    # 如果用户登陆则进入个人中心
    # 如果没有登陆,跳转主页
    # 返回用户数据
    if not g.user:
        return redirect("/")
    data = {
        "user":g.user
    }
    return make_response(render_template('news/user.html',data=data),constants.PAGE_NET_TAG)

# 用户基础页
@profile_blu.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    # 不同的请求方式，做不同的事情
    # 如果是GET请求,返回用户数据
    if request.method == "GET":
        data = {"user":g.user.to_dict()}
        return make_response(render_template("news/user_base_info.html",data=data),constants.PAGE_NET_TAG)
    else:
        # 获取传入参数
        nick_name = request.json.get('nick_name')
        signature = request.json.get('signature')
        gender = request.json.get('gender')
        # 校验参数
        if not all([nick_name,signature,gender]):
            data = {
                "errno":constants.WRONG_INPUT_TAG,
                "errmsg":"数据不完整(有空)"
            }
            return jsonify(data)
        if gender not in ["MAN","WOMAN"]:
            data = {
                "errno":constants.WRONG_INPUT_TAG,
                "errmsg":"性别参数异常"
            }
            return jsonify(data)
        # 修改用户数据
        g.user.nick_name=nick_name
        g.user.signature=signature
        g.user.gender=gender
        try:
            db.session.commit()
        except Exception as e:
            logging.error("Mysql数据库出错,错误原因%s"%e)
            db.session.rollback()
            data = {
                "errno":constants.SYSTEM_WRONE_TAG,
                "errmsg":"系统异常"
            }
            return jsonify(data)
        # 返回正确信息
        data = {
            "errno":constants.CORRECT_TAG,
            "errmsg":"信息修改成功"
        }
        return jsonify(data)

# 用户头像页
@profile_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    if request.method == "GET":
        user = g.user
        data = {
            "user":user
        }
        return make_response(render_template('news/user_pic_info.html', data=data),constants.PAGE_NET_TAG)
    else:
        urlnet = "/static/media/user/"
        newpic = request.files.get("newpic")
        picname = request.form.get("picname")
        endt ="." + picname.split(".")[-1]
        if not g.user.avatar_url:
            uid = str(uuid4()).replace("-","")
            fpath = os.path.join(constants.MEDIAFLODER,"user", uid + endt)
            newpic.save(fpath)
            urlnet = urlnet+uid+endt
            g.user.avatar_url = urlnet
            try:
                db.session.commit()
            except Exception as e:
                logging.error("图片上传失败,失败原因为%s"%e)
                data = {
                    "errno":constants.SYSTEM_WRONE_TAG,
                    "errmsg":"系统错误"
                }
                os.remove(fpath)
                db.session.rollback()
                return jsonify({"data":data})
        else:
            filename = os.path.basename(g.user.avatar_url)
            oldfilepath = os.path.join(constants.MEDIAFLODER,"user",filename)
            uid = str(uuid4()).replace("-", "")
            fpath = os.path.join(constants.MEDIAFLODER,"user", uid + endt)
            newpic.save(fpath)
            urlnet = urlnet + uid + endt
            g.user.avatar_url = urlnet
            try:
                db.session.commit()
                os.remove(oldfilepath)
            except Exception as e:
                logging.error("图片上传失败,失败原因为%s" % e)
                data = {
                    "errno": constants.SYSTEM_WRONE_TAG,
                    "errmsg": "系统错误"
                }
                os.remove(fpath)
                db.session.rollback()
                return jsonify({"data": data})
        data = {
            "avatar_url":urlnet
        }
        return jsonify({"data":data,"errno":constants.CORRECT_TAG})

# 密码修改
@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    if request.method == "GET":
        return make_response(render_template('news/user_pass_info.html'),constants.PAGE_NET_TAG)
    else:
        # 1. 获取参数
        old_password = request.json.get('old_password')
        new_password = request.json.get('new_password')
        new_password2 = request.json.get('new_password2')
        # 2. 校验参数
        if not all([old_password,new_password,new_password2]):
            data = {
                "errno":constants.WRONG_INPUT_TAG,
                "errmsg":"参数不完整"
            }
            return jsonify(data)
        if new_password!=new_password2:
            data = {
                "errno":constants.WRONG_INPUT_TAG,
                "errmsg":"两次密码不同"
            }
            return jsonify(data)

        # 3. 判断旧密码是否正确
        rls = g.user.check_password(old_password)
        if not rls:
            data = {
                "errno":constants.WRONG_INPUT_TAG,
                "errmsg":"原密码错误"
            }
            return jsonify(data)
        # 4. 设置新密码
        g.user.password = new_password
        try:
            db.session.commit()
        except Exception as e:
            data = {
                "errno":constants.SYSTEM_WRONE_TAG,
                "errmsg":"系统出错"
            }
            return jsonify(data)
        data = {
            "errno":constants.CORRECT_TAG
        }
        return jsonify(data)

# 用户收藏
@profile_blu.route('/collection')
@user_login_data
def user_collection():
     # 1. 获取参数
    p = request.args.get("p", 1)
    # 2. 判断参数
    try:
        p = int(p)
    except Exception as e:
        return render_template('news/404.html')
    # 3. 查询用户指定页数的收藏的新闻

        # 进行分页数据查询
    try:
        collections = g.user.collection_news.paginate(page=p, per_page=constants.USER_COLLECTION_MAX_NEWS, error_out=False)
    except Exception as e:
        logging.error("Mysql数据库异常,异常原因%s"%e)
        return redirect("/500.html")
    # 当前页数
    current_page = p
    # 总页数
    total_page = collections.pages
    # 总数据
	# 返回数据
    data = {
        "collections": collections.items,
        "total_page":total_page,
        "current_page":current_page
    }
    return make_response(render_template('news/user_collection.html', data=data),constants.PAGE_NET_TAG)

# 发布新闻
@profile_blu.route('/news_release', methods=["GET", "POST"])
@user_login_data
def news_release():
    # GET请求
    if request.method == "GET":
        # 1. 加载新闻分类数据
        try:
            categories = Category.query.filter(Category.name!="最新").all()
        except Exception as e:
            logging.error("数据库异常,异常原因%s"%e)
            return redirect("/500.html")
        # 2. 移除最新分类
        data = {
            "categories":categories
        }
        # 返回数据
        return make_response(render_template("news/user_news_release.html",**data),constants.PAGE_NET_TAG)
    else:
        # 1. 获取要提交的数据
        title = request.form.get('title')
        category_id = request.form.get('category_id')
        digest  = request.form.get('digest')
        index_image_file = request.files.get('index_image')
        # index_image_name = index_image_file.filename
        source = request.form.get('source')
        content = request.form.get('content')
        # 校验参数
        if not [title,category_id,digest,index_image_file,content,source]:
            return jsonify({"errno":constants.WRONG_INPUT_TAG,"errmsg":"参数不完整"})
        index_image_name = index_image_file.filename
        # 3.取到图片，将图片上传到七牛云
        dirpath = constants.MEDIAFLODER
        filename = str(uuid4()).replace("-","")+"."+os.path.split(index_image_name)[-1]
        fpath = os.path.join(dirpath,"news",filename)
        index_image_file.save(fpath)
        repath = "/static/media/news/"+filename
        # 保存数据
        try:
            news = News()
            news.user_id =g.user.id
            news.category_id =category_id
            news.digest = digest
            news.source = source
            news.title = title
            news.index_image_url = repath
            news.content = content
            # 新闻状态,将新闻设置为1代表待审核状态
            # 手动设置新闻状态,在返回前commit提交
            # 返回
            news.status = 1
            db.session.add(news)
            db.session.commit()
            data = {
                "errno":constants.CORRECT_TAG
            }
            return jsonify(data)
        except Exception as e:
            logging.error("数据库出错,错误原因%s"%e)
            db.rollback()
            os.remove(fpath)
            data = {
                "errno":constants.SYSTEM_WRONE_TAG,
                "errmsg":"系统异常"
            }
            return jsonify(data)

# Todo 新闻列表
@profile_blu.route('/news_list')
@user_login_data
def news_list():
    p = request.args.get("p","1")
    try:
        p= int(p)
    except:
        return redirect('/user/news_list')
    try:
        news = News.query.filter(News.user_id==g.user.id).paginate(page=p, per_page=constants.USER_COLLECTION_MAX_NEWS, error_out=False)
    except Exception as e:
        logging.error("系统出错,出错原因%s"%e)
        return redirect("/500.html")
    data = {
        "news_list":news.items,
        "current_page":p,
        "total_page":news.pages
    }
    return make_response(render_template('news/user_news_list.html',data=data),200)

@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return make_response(render_template('news/user_follow.html', data=data),200)

@profile_blu.route('/other_info')
@user_login_data
def other_info():
    user = g.user

    # 去查询其他人的用户信息
    other_id = request.args.get("id")

    if not other_id:
        abort(404)

    # 查询指定id的用户信息
    other = None
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if other and user:
        if other in user.followed:
            is_followed = True

    data = {
        "is_followed": is_followed,
        "user": g.user,
        "other_info": other,
    }
    return render_template('news/other.html', data=data)

@profile_blu.route('/other_news_list')
def other_news_list():
    """返回指定用户的发布的新闻"""

    # 1. 取参数
    other_id = request.args.get("user_id")
    page = request.args.get("p", 1)

    # 2. 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=constants.WRONG_INPUT_TAG, errmsg="参数错误")

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=constants.SYSTEM_WRONE_TAG, errmsg="数据查询失败")

    if not other:
        return jsonify(errno=constants.WRONG_INPUT_TAG, errmsg="当前用户不存在")

    try:
        paginate = other.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=constants.SYSTEM_WRONE_TAG, errmsg="数据查询失败")

    news_dict_list = []
    for news_item in news_li:
        news_dict_list.append(news_item.to_basic_dict())

    data = {
        "news_list": news_dict_list,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=constants.CORRECT_TAG, errmsg="OK", data=data)






